package utils

import (
	"bytes"
	"github.com/360EntSecGroup-Skylar/excelize"
	"io/ioutil"
	"mime/multipart"
	"strings"
)

// 获取excel文件流并解析数据
func GetExcelDataByFile(file multipart.File, sheet string) ([][]string, error) {
	body, _ := ioutil.ReadAll(file)
	xlsx, err := excelize.OpenReader(bytes.NewReader(body))
	if err != nil {
		return nil, err
	}
	return xlsx.GetRows(sheet), nil
}

// 导出数据过滤
func DisposeExcelData(data [][]string) [][]string {
	if len(data) == 0 {
		return data
	}

	// 数据整理
	newData := make([][]string, 0)
	for k, v := range data {
		if k == 0 {
			newData = append(newData, v)
			continue
		}
		tInfo := make([]string, 0)
		iNull := 0
		for _, vv := range v {
			if len(vv) == 0 {
				iNull++
			} else {
				vv = strings.Trim(vv, " ")
			}
			// 去除前后空格
			tInfo = append(tInfo, vv)
		}
		// 整行为空则过滤
		if iNull == len(v) {
			continue
		}
		newData = append(newData, tInfo)
	}

	return data
}
